#include <unistd.h> // usleep
#include "Worker.h"
#include "Sunnet.h"

using namespace std;

void Worker::operator()() {
    while (true) {
        shared_ptr<Service> srv = Sunnet::instance->PopGlobalQueue();
        if (!srv) {
            Sunnet::instance->WorkerWait();
        } else {
            srv->ProcessMsgs(eachNum);
            CheckAndPutGlobal(srv);
        }

        // usleep(1000 * 1000);
    }
}

void Worker::CheckAndPutGlobal(shared_ptr<Service> srv) {
    if (srv->isExiting) {
        return ;
    }
    pthread_spin_lock(&srv->queueLock);
    {
        if (!srv->msgQueue.empty()) {
            // srv->inGloabl 一定是true
            Sunnet::instance->PushGlobalQueue(srv);
        } else {
            srv->SetInGlobal(false);
        }
    }
    pthread_spin_unlock(&srv->queueLock);
}
